<template>

  <!--
  用户模块
  采用前端搜索和分页
   -->
  <div class="gx-panel">

    <!-- 新增和修改弹层 -->
    <el-dialog
    :close-on-click-modal="false"
    :title="(action==='add'?'新增':'修改')+'用户'"
    :visible.sync="visible"
    width="430px"
    @closed="$refs.form.clearValidate()"
    >

      <!-- 表单 -->
      <el-form label-width="90px" :model="form" :rules="rules" ref="form">

        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>

        <el-form-item
        label="密码"
        prop="password"
        :rules="{required: action==='add', message: '请输入密码！'}"
        >
          <el-input 
          type="password"
          v-model="form.password"
          :placeholder="action==='edit'?'不修改则保持为空!':''"
          />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile" />
        </el-form-item>

        <el-form-item label="上传头像" prop="avatar">
          <el-input v-model="form.avatar">
            <el-upload
            action="http://cloud.scnew.com.cn/api/user/upload"
            slot="append"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            >
              <el-button icon="el-icon-upload2"/>
            </el-upload>
          </el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio v-model="form.gender" :label="1">女</el-radio>
          <el-radio v-model="form.gender" :label="2">男</el-radio>
        </el-form-item>

        <el-form-item label="所属角色" prop="role">
          <el-select v-model="form.role" clearable>
            <el-option
            v-for="item in []"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            />
          </el-select>

        </el-form-item>

        <el-form-item label="审核">
          <el-switch 
          v-model="form.state" 
          :active-value="2" 
          :inactive-value="1"
          /> 
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>

    </el-dialog>

    <div class="heading">
      <h1>用户管理</h1>
      <el-breadcrumb>
        <el-breadcrumb-item to="/control">后台首页</el-breadcrumb-item>
        <el-breadcrumb-item to="/control/admin">用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="search">
  
      <el-form :inline="true">

        <el-form-item v-if="ids.length">
          <el-button type="danger" size="small" @click="handleRemove(ids)">批量删除</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-select 
          v-model="condition.state" 
          placeholder="选择审核"
          clearable
          size="small"
          style="width:120px"
          >
            <el-option label="未审核" :value="1" />
            <el-option label="已审核" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-input 
          v-model.trim="condition.keyword" 
          placeholder="请输入账号/昵称/手机"
          size="small"
          clearable
          />
        </el-form-item>

      </el-form>

      <el-button 
      type="primary" 
      icon="el-icon-plus" 
      size="small"
      @click="add"
      >新增</el-button>

    </div>

    <div class="datagrid">

      <el-table
      :data="pageData"
      style="width:100%"
      @selection-change="handleSelectionChange"
      ref="table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="头像" v-slot="scope">
          <el-image 
          style="height:40px" 
          :src="scope.row.avatar"
          fit="cover"
          />
        </el-table-column>
        <el-table-column label="账号" prop="username" />
        <el-table-column label="昵称" prop="nickname" />
        <el-table-column label="手机" prop="mobile" />
        <el-table-column label="注册日期" :formatter="handleDate" prop="pubdate" sortable />
        <el-table-column label="审核" v-slot="scope" :width="110">
          <el-switch 
          v-model="scope.row.state"
          :active-value="2"
          :inactive-value="1"
          @change="handleSwitchChange(scope.row)"
          />
        </el-table-column>

        <el-table-column label="操作" :width="170" v-slot="scope">
          <el-button 
          size="mini"
          @click="edit(scope.row)"
          >修改</el-button>
          <el-button 
          type="danger" 
          size="mini"
          @click="handleRemove([scope.row.id])"
          >删除</el-button>
        </el-table-column>
      </el-table>

      <el-pagination
      class="gx-pagination"
      background
      :current-page.sync="page"
      :page-size.sync="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[1, 2, 3]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="searchData.length" />
    </div>

  </div>
</template>

<script>
import moment from 'moment'
import {pick} from '@/utils'
export default {
  data(){
    return {
      visible: false,
      action: 'add',
      form: {},
      rules: {
        username: {required: true, message: '请输入账号'},
        nickname: {required: true, message: '请输入昵称'},
      },

      condition: {},
      listData: [],
      //复选框选中的id值
      ids: [],

      //分页信息 pageSize 每页多少条
      page: 1,
      pageSize: 3,
    }
  },
  computed: {
    searchData(){
      let {state, keyword} = this.condition;
      return this.listData.filter(item => {
        return (state ? item.state === state : true) && 
               (keyword ? [item.username,item.nickname,item.mobile].some(item=>item.includes(keyword)) : true);
      })
    },
    pageData(){
      let start = (this.page-1) * this.pageSize;
      let end = start + this.pageSize;
      return this.searchData.slice(start, end);
    }
  },
  created(){
    this.query()
  },
  methods: {
    query(){
      this.$http.get('admin/list').then(res => {
        if(res.err > 0){
          this.$message.error(res.desc);
        }else{
          this.listData = res.result
        }
      })
    },
    handleDate( row ){
      return moment( row.pubdate ).format('YYYY年MM月DD日');
    },
    handleSelectionChange( arr ){
      this.ids = arr.map(item => item.id);
    },
    handleCurrentChange( page ){
      this.page = page;
    },
    handleSizeChange( size ){
      this.pageSize = size;
    },
    handleSwitchChange({id, state}){
      this.$http.post('admin/state', { id, state }).then(res => {
        if(res.err > 0){
          this.$message.error(res.desc);
        }else{
          this.$message.success(res.desc);
        }
      }) 
    },
    handleRemove( ids ){

      this.$confirm('您确定删除所选数据吗？', '提示').then(() => {

        this.$http.post('admin/remove', {ids}).then(res => {
          if(res.err > 0){
            this.$message.error(res.desc);
          }else{
            this.query();
            this.$message.success(res.desc);
          }
        })
        
      }).catch(_ => {

        //调用table组件的methods方法 clearSelection 清除选择
        this.$refs.table.clearSelection();

      })

    },
    add(){
      this.visible = true;
      this.action = 'add';
      this.form = { state: 2};
    },
    edit( row ){
      this.visible = true;
      this.action = 'edit';
      this.form = pick(row, ['id','username','nickname','mobile','avatar','gender','role','state']);
    },
    save(){

      this.$refs.form.validate( vaild => {
        if( vaild ){
          
          this.$http.post(`admin/${this.action}`, this.form).then(res => {
            if(res.err > 0){
              this.$message.error(res.desc);
            }else{
              this.query();
              this.$message.success(res.desc);
              this.visible = false;
            }
          })

        }
      })

    },
    beforeUpload (file) {
      const ext = file.name.match(/\.(\w+)$/i)[1].toLowerCase()
      const isPic = ['jpeg', 'png', 'gif', 'jpg', 'webp']
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPic.includes(ext)) this.$message.error('上传图片只能是 ' + isPic + ' 格式!')
      if (!isLt2M) this.$message.error('上传图片大小不能超过 2MB!')
      return isPic && isLt2M
    },
    uploadSuccess (res) {
      if (res.err > 0) {
        this.$message.error(res.desc)
      } else {
        this.$message.success(res.desc)
        this.$set(this.form, 'avatar', res.result)
      }
    }
  }
}
</script>